package com.scm.biz.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.scm.biz.bean.SysRole;
import com.scm.biz.bean.SysUser;
import com.scm.biz.dto.LoginDto;
import com.scm.biz.enums.LogOperation;
import com.scm.biz.service.ResourceService;
import com.scm.biz.service.SysRoleService;
import com.scm.biz.service.SysUserRoleService;
import com.scm.biz.service.SysUserService;
import com.scm.core.bean.resp.RespBean;
import com.scm.core.constant.ConfigProperties;
import com.scm.core.interceptor.LogConfig;
import com.scm.utils.UfdmMd5Util;
@Controller
public class MainAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1534072083803555570L;
	@Resource
	ResourceService resourceService;
	@Resource
	SysUserService sysUserService;
	@Resource
	SysRoleService sysRoleService;
	@RequestMapping("/validate")
	@ResponseBody
	@LogConfig(operationModule=LogOperation.LOGIN,description="用户登录")
	public RespBean<String> validate(LoginDto loginDto,HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		if(loginDto.getLoginCode()==null || loginDto.getLoginCode().equals("")){
			throw new Exception("账号不能为空");
		}
		if(loginDto.getPassword()==null || loginDto.getPassword().equals("")){
			throw new Exception("密码不能为空");
		}
        SecurityUtils.getSubject().login(new UsernamePasswordToken(loginDto.getLoginCode(), UfdmMd5Util.MD5Encode(loginDto.getPassword()))); 
	    RespBean<String> respBean = new RespBean<String>();
	    try {  
	    	respBean.setBody("success");
	    	
	    	SecurityUtils.getSubject().getSession().setAttribute("userCode", loginDto.getLoginCode());
            return respBean;   
	    } catch (AuthenticationException  e) {    
	        throw new Exception("用户名或密码错误");
	    } 
	}
	@RequestMapping("/index")
	public ModelAndView index(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		ModelAndView mv = new ModelAndView("index");
		List<com.scm.biz.bean.Resource> menuList = new ArrayList<com.scm.biz.bean.Resource>();
		Map<String, com.scm.biz.bean.Resource> permisionMap = new HashMap<String,com.scm.biz.bean.Resource>();
		for(com.scm.biz.bean.Resource resource:resourceService.selectList()){
			if(SecurityUtils.getSubject().isPermitted(resource.getCode())){
				if(resource.getCategory().length()==3){
					menuList.add(resource);
				}
				if(resource.getCategory().length()==5){
					permisionMap.put(resource.getCode(), resource);
				}
				
			}
		}
		String loginCode = SecurityUtils.getSubject().getSession().getAttribute("userCode").toString();
		SysUser sysUser = sysUserService.selectByEmail(loginCode);
		SecurityUtils.getSubject().getSession().setAttribute("userId", sysUser.getId());
		SecurityUtils.getSubject().getSession().setAttribute("sysUser", sysUser);
		SecurityUtils.getSubject().getSession().setAttribute("domainUrl", ConfigProperties.properties.get("domainUrl"));
		SecurityUtils.getSubject().getSession().setAttribute("menuList", menuList);
		SecurityUtils.getSubject().getSession().setAttribute("permisionMap", permisionMap);
		SecurityUtils.getSubject().getSession().setAttribute("isLogin", "ok");

		SecurityUtils.getSubject().getSession().setAttribute("_roleList", sysRoleService.selectListByUserId(sysUser.getId()));
		return mv;
	}
	@RequestMapping("/login")
	public ModelAndView login(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("login");
		
		return mv;
	}
	@RequestMapping("/logout")
	public ModelAndView logout(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("login");
		SecurityUtils.getSubject().logout(); 
		return mv;
	}
	 
}
